import pathlib
import time
import re
import typing
import os
import rich.traceback
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
import enum
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *

# 导入 rich 组件
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.table import Table
from rich.columns import Columns
from rich.align import Align
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
from rich.prompt import Prompt
from rich.markdown import Markdown
from rich.syntax import Syntax
from rich.tree import Tree
from rich.layout import Layout
from rich.live import Live
from rich.box import ROUNDED, DOUBLE, HEAVY

# 初始化rich跟踪回溯和控制台
rich.traceback.install()
console = Console()

# ------------------------------
# 样式配置
# ------------------------------
class Styles:
    """样式配置类"""
    SUCCESS = "bold green"
    ERROR = "bold red"
    WARNING = "bold yellow"
    INFO = "bold blue"
    HIGHLIGHT = "bold cyan"
    STEP = "bold magenta"
    CONDITION = "bold white"
    ELEMENT = "bold bright_white"
    SECTION = "bold bright_white"
    OPERATION = "bold bright_green"

# ------------------------------
# 条件类型枚举定义
# ------------------------------
class ConditionType(enum.Enum):
    """元素验证条件的枚举类型"""
    # 输入框值验证
    InputValueIsNull = 1          # 输入框值为空
    InputValueIsNotNull = 2       # 输入框值不为空
    InputValueEqual = 3           # 输入框值等于指定值
    InputValueNotEqual = 4        # 输入框值不等于指定值
    InputValueInclude = 5         # 输入框值包含指定内容
    InputValueNotInclude = 6      # 输入框值不包含指定内容
    
    # 文本内容验证
    TextValueIsNull = 7           # 文本内容为空
    TextValueIsNotNull = 8        # 文本内容不为空
    TextValueEqual = 9            # 文本内容等于指定值
    TextValueNotEqual = 10        # 文本内容不等于指定值
    TextValueInclude = 11         # 文本内容包含指定内容
    TextValueNotInclude = 12      # 文本内容不包含指定内容
    
    # 元素状态验证
    ElementIsEnabled = 13         # 元素可用
    ElementIsDisabled = 14        # 元素不可用
    ElementIsVisible = 15         # 元素可见
    ElementIsInvisible = 16       # 元素不可见
    ElementIsSelected = 17        # 元素被选中
    ElementIsNotSelected = 18     # 元素未被选中

# ------------------------------
# 输出美化工具类
# ------------------------------
class OutputDecorator:
    """输出美化装饰器"""
    
    @staticmethod
    def create_operation_panel(title: str, content: str, border_style: str = "blue", box_type=ROUNDED):
        """创建操作面板，包裹整个操作过程"""
        return Panel(
            content,
            title=f"🔹 {title}",
            title_align="left",
            border_style=border_style,
            box=box_type,
            padding=(1, 2)
        )
    
    @staticmethod
    def create_step_panel(step_name: str, content: str, status: str = "info", icon: str = "📋"):
        """创建步骤面板"""
        status_colors = {
            "success": "green",
            "error": "red", 
            "warning": "yellow",
            "info": "blue"
        }
        
        border_color = status_colors.get(status, "blue")
        status_icon = {
            "success": "✅",
            "error": "❌",
            "warning": "⚠️",
            "info": "ℹ️"
        }.get(status, "📋")
        
        return Panel(
            content,
            title=f"{status_icon} {step_name}",
            border_style=border_color,
            box=ROUNDED,
            padding=(0, 1)
        )
    
    @staticmethod
    def create_condition_table(condition_type: str, xpath: str, expected_value: str = None, status: str = "pending"):
        """创建条件验证表格"""
        status_icons = {
            "pending": "⏳",
            "success": "✅",
            "error": "❌"
        }
        
        table = Table(show_header=False, box=None, padding=(0, 1))
        table.add_column("属性", style=Styles.CONDITION, width=12)
        table.add_column("值", style=Styles.INFO)
        
        icon = status_icons.get(status, "⏳")
        table.add_row("状态", f"{icon} {status}")
        table.add_row("条件类型", f"[{Styles.HIGHLIGHT}]{condition_type}[/{Styles.HIGHLIGHT}]")
        table.add_row("XPath", f"[{Styles.ELEMENT}]{xpath}[/{Styles.ELEMENT}]")
        if expected_value:
            table.add_row("预期值", f"[{Styles.HIGHLIGHT}]{expected_value}[/{Styles.HIGHLIGHT}]")
        
        return table
    
    @staticmethod
    def create_element_info_table(xpath: str, timeout: int, retry_count: int):
        """创建元素信息表格"""
        table = Table(show_header=False, box=None, padding=(0, 1))
        table.add_column("属性", style=Styles.CONDITION, width=12)
        table.add_column("值", style=Styles.INFO)
        
        table.add_row("目标XPath", f"[{Styles.ELEMENT}]{xpath}[/{Styles.ELEMENT}]")
        table.add_row("超时时间", f"{timeout}秒")
        table.add_row("重试次数", f"{retry_count}次")
        
        return table
    
    @staticmethod
    def create_action_info_table(action_type: str, details: str, target: str):
        """创建操作信息表格"""
        table = Table(show_header=False, box=None, padding=(0, 1))
        table.add_column("属性", style=Styles.CONDITION, width=12)
        table.add_column("值", style=Styles.INFO)
        
        table.add_row("操作类型", f"[{Styles.HIGHLIGHT}]{action_type}[/{Styles.HIGHLIGHT}]")
        table.add_row("操作详情", f"[{Styles.INFO}]{details}[/{Styles.INFO}]")
        table.add_row("目标元素", f"[{Styles.ELEMENT}]{target}[/{Styles.ELEMENT}]")
        
        return table
    
    @staticmethod
    def print_operation_header(operation_type: str, operation_name: str, icon: str = "🚀"):
        """打印操作头部"""
        console.print()
        console.rule(f"{icon} {operation_type}: {operation_name}", style=Styles.OPERATION)
        console.print()

# ------------------------------
# 条件验证器类
# ------------------------------
class ConditionVerifier:
    """条件验证器，负责前置条件和后置条件的验证逻辑"""
    
    @staticmethod
    def verify_condition(
        driver: WebDriver,
        xpath: str,
        condition_type: typing.Optional[ConditionType] = None,
        expected_value: typing.Optional[str] = None,
        timeout: int = 10,
        loop_interval: float = 0.1,
        condition_name: str = "条件验证"
    ) -> bool:
        """
        验证指定元素是否满足条件
        """
        if not xpath:  # 空XPath视为条件自动满足
            return True
            
        condition_type_name = condition_type.name if condition_type else "无条件"
        
        # 创建条件信息面板
        condition_table = OutputDecorator.create_condition_table(
            condition_type_name, xpath, expected_value, "pending"
        )
        
        condition_panel = OutputDecorator.create_step_panel(
            condition_name, 
            condition_table,
            "info",
            "🔍"
        )
        console.print(condition_panel)
        
        start_time = datetime.datetime.now()
        result = False
        
        # 使用状态显示验证过程
        with console.status(f"[bold blue]验证条件中...[/bold blue]", spinner="dots"):
            while start_time + datetime.timedelta(seconds=timeout) > datetime.datetime.now():
                try:
                    element = driver.find_element(by=By.XPATH, value=xpath)
                    
                    # 根据条件类型进行验证
                    if not condition_type:
                        result = True
                        break
                        
                    # 输入框值验证
                    elif condition_type == ConditionType.InputValueIsNull:
                        result = element.get_attribute("value") == ""
                    elif condition_type == ConditionType.InputValueIsNotNull:
                        result = element.get_attribute("value") != ""
                    elif condition_type == ConditionType.InputValueEqual:
                        result = element.get_attribute("value") == expected_value
                    elif condition_type == ConditionType.InputValueNotEqual:
                        result = element.get_attribute("value") != expected_value
                    elif condition_type == ConditionType.InputValueInclude:
                        result = expected_value in element.get_attribute("value") if expected_value else False
                    elif condition_type == ConditionType.InputValueNotInclude:
                        result = expected_value not in element.get_attribute("value") if expected_value else True
                        
                    # 文本内容验证
                    elif condition_type == ConditionType.TextValueIsNull:
                        result = element.text == ""
                    elif condition_type == ConditionType.TextValueIsNotNull:
                        result = element.text != ""
                    elif condition_type == ConditionType.TextValueEqual:
                        result = element.text == expected_value
                    elif condition_type == ConditionType.TextValueNotEqual:
                        result = element.text != expected_value
                    elif condition_type == ConditionType.TextValueInclude:
                        result = expected_value in element.text if expected_value else False
                    elif condition_type == ConditionType.TextValueNotInclude:
                        result = expected_value not in element.text if expected_value else True
                    
                    # 元素状态验证
                    elif condition_type == ConditionType.ElementIsEnabled:
                        result = element.is_enabled()
                    elif condition_type == ConditionType.ElementIsDisabled:
                        result = not element.is_enabled()
                    elif condition_type == ConditionType.ElementIsVisible:
                        result = element.is_displayed()
                    elif condition_type == ConditionType.ElementIsInvisible:
                        result = not element.is_displayed()
                    elif condition_type == ConditionType.ElementIsSelected:
                        result = element.is_selected()
                    elif condition_type == ConditionType.ElementIsNotSelected:
                        result = not element.is_selected()
                    
                    if result:
                        break
                        
                except NoSuchElementException:
                    pass  # 元素未找到，继续等待
                except Exception as e:
                    console.print(f"[{Styles.ERROR}]验证错误: {str(e)}[/{Styles.ERROR}]")
                    
                time.sleep(loop_interval)
        
        # 显示验证结果
        result_table = OutputDecorator.create_condition_table(
            condition_type_name, xpath, expected_value, 
            "success" if result else "error"
        )
        
        result_panel = OutputDecorator.create_step_panel(
            f"{condition_name} - {'成功' if result else '失败'}", 
            result_table,
            "success" if result else "error",
            "✅" if result else "❌"
        )
        console.print(result_panel)
        
        return result

# ------------------------------
# 元素查找器类
# ------------------------------
class ElementFinder:
    """元素查找器，只负责查找元素"""
    
    @staticmethod
    def find_element(
        driver: WebDriver,
        target_xpath: str,
        step_name: str = "元素查找",
        # 前置条件参数（可选）
        precondition_xpath: str = None,
        precondition_type: ConditionType = None,
        precondition_value: str = None,
        # 查找配置
        timeout: int = 10,
        retry_count: int = 0,
        loop_interval: float = 0.1,
        terminate_on_failure: bool = False
    ) -> typing.Optional[WebElement]:
        """
        查找元素（可选的预处理条件）
        """
        max_attempts = retry_count + 1
        attempt = 0
        
        # 创建操作主面板内容
        operation_content = []
        
        while attempt < max_attempts:
            attempt += 1
            
            # 操作头部
            OutputDecorator.print_operation_header("元素查找", step_name, "🔍")
            
            # 创建查找信息面板
            element_table = OutputDecorator.create_element_info_table(target_xpath, timeout, retry_count)
            element_panel = OutputDecorator.create_step_panel(
                "查找配置", 
                element_table,
                "info",
                "⚙️"
            )
            console.print(element_panel)
            
            # ==================== 1. 前置条件验证（可选） ====================
            if precondition_xpath:
                pre_conditions_met = ConditionVerifier.verify_condition(
                    driver=driver,
                    xpath=precondition_xpath,
                    condition_type=precondition_type,
                    expected_value=precondition_value,
                    timeout=timeout,
                    loop_interval=loop_interval,
                    condition_name="前置条件验证"
                )
                
                if not pre_conditions_met:
                    if terminate_on_failure:
                        console.print()
                        error_panel = OutputDecorator.create_step_panel(
                            "操作终止", 
                            "前置条件未满足，程序终止执行",
                            "error",
                            "🚨"
                        )
                        console.print(error_panel)
                        exit(0)
                    
                    retry_panel = OutputDecorator.create_step_panel(
                        "重试操作", 
                        f"前置条件未满足，将进行重试 ({attempt}/{max_attempts})",
                        "warning",
                        "🔄"
                    )
                    console.print(retry_panel)
                    continue
            
            # ==================== 2. 目标元素查找 ====================
            console.print()
            finding_panel = OutputDecorator.create_step_panel(
                "查找元素", 
                f"正在查找元素: [{Styles.ELEMENT}]{target_xpath}[/{Styles.ELEMENT}]",
                "info",
                "🎯"
            )
            console.print(finding_panel)
            
            target_element = None
            start_time = datetime.datetime.now()
            
            # 查找元素
            with console.status(f"[bold blue]查找目标元素中...[/bold blue]", spinner="dots"):
                while start_time + datetime.timedelta(seconds=timeout) > datetime.datetime.now():
                    try:
                        target_element = driver.find_element(By.XPATH, target_xpath)
                        break
                    except NoSuchElementException:
                        time.sleep(loop_interval)
                        continue
            
            if not target_element:
                retry_panel = OutputDecorator.create_step_panel(
                    "查找失败", 
                    f"未找到目标元素，将进行重试 ({attempt}/{max_attempts})",
                    "warning",
                    "🔄"
                )
                console.print(retry_panel)
                continue
                
            # 查找成功
            success_panel = OutputDecorator.create_step_panel(
                "查找成功", 
                f"成功找到目标元素: [{Styles.ELEMENT}]{target_xpath}[/{Styles.ELEMENT}]",
                "success",
                "✅"
            )
            console.print(success_panel)
            
            # ==================== 3. 操作完成 ====================
            console.print()
            summary_table = Table(show_header=False, box=None, padding=(0, 1))
            summary_table.add_column("项目", style=Styles.CONDITION, width=12)
            summary_table.add_column("结果", style=Styles.INFO)
            
            summary_table.add_row("操作类型", "元素查找")
            summary_table.add_row("步骤名称", step_name)
            summary_table.add_row("尝试次数", f"{attempt}/{max_attempts}")
            summary_table.add_row("目标元素", target_xpath)
            summary_table.add_row("执行结果", "✅ 成功")
            
            summary_panel = OutputDecorator.create_operation_panel(
                "操作完成",
                summary_table,
                "green",
                DOUBLE
            )
            console.print(summary_panel)
            console.print()
            
            return target_element

        # ==================== 4. 所有尝试都失败 ====================
        error_table = Table(show_header=False, box=None, padding=(0, 1))
        error_table.add_column("项目", style=Styles.CONDITION, width=12)
        error_table.add_column("结果", style=Styles.INFO)
        
        error_table.add_row("操作类型", "元素查找")
        error_table.add_row("步骤名称", step_name)
        error_table.add_row("最大尝试", f"{max_attempts}次")
        error_table.add_row("目标元素", target_xpath)
        error_table.add_row("执行结果", "❌ 失败")
        
        error_panel = OutputDecorator.create_operation_panel(
            "操作失败",
            error_table,
            "red",
            HEAVY
        )
        console.print(error_panel)
        console.print()
        
        return None

# ------------------------------
# 鼠标操作工具类
# ------------------------------
class MouseOperator:
    """鼠标操作工具类，提供带条件验证的鼠标操作"""
    
    @staticmethod
    def click_element(
        driver: WebDriver,
        target_xpath: str,
        step_name: str = "点击操作",
        # 操作前条件参数
        pre_condition_xpath: str = None,
        pre_condition_type: ConditionType = None,
        pre_condition_value: str = None,
        # 操作后条件参数
        post_condition_xpath: str = None,
        post_condition_type: ConditionType = None,
        post_condition_value: str = None,
        # 元素状态条件
        element_condition_type: ConditionType = ConditionType.ElementIsEnabled,
        # 通用参数
        timeout: int = 10,
        retry_count: int = 0,
        loop_interval: float = 0.1,
        terminate_on_failure: bool = False
    ) -> bool:
        """
        带条件验证的元素点击操作
        """
        max_attempts = retry_count + 1
        attempt = 0
        
        while attempt < max_attempts:
            attempt += 1
            
            # 操作头部
            OutputDecorator.print_operation_header("鼠标点击", step_name, "🖱️")
            
            # 创建操作信息面板
            action_table = OutputDecorator.create_action_info_table(
                "鼠标点击", 
                "执行元素点击操作",
                target_xpath
            )
            action_panel = OutputDecorator.create_step_panel(
                "操作配置", 
                action_table,
                "info",
                "⚙️"
            )
            console.print(action_panel)
            
            # ==================== 1. 前置条件验证 ====================
            if pre_condition_xpath:
                pre_conditions_met = ConditionVerifier.verify_condition(
                    driver=driver,
                    xpath=pre_condition_xpath,
                    condition_type=pre_condition_type,
                    expected_value=pre_condition_value,
                    timeout=timeout,
                    loop_interval=loop_interval,
                    condition_name="执行前条件验证"
                )
                
                if not pre_conditions_met:
                    if terminate_on_failure:
                        console.print()
                        error_panel = OutputDecorator.create_step_panel(
                            "操作终止", 
                            "前置条件未满足，程序终止执行",
                            "error",
                            "🚨"
                        )
                        console.print(error_panel)
                        exit(0)
                    
                    retry_panel = OutputDecorator.create_step_panel(
                        "重试操作", 
                        f"前置条件未满足，将进行重试 ({attempt}/{max_attempts})",
                        "warning",
                        "🔄"
                    )
                    console.print(retry_panel)
                    continue
            
            # ==================== 2. 查找目标元素 ====================
            console.print()
            target_element = ElementFinder.find_element(
                driver=driver,
                target_xpath=target_xpath,
                step_name=f"{step_name} - 查找点击目标",
                timeout=timeout,
                retry_count=0,  # 点击操作本身有重试，这里不重复重试
                loop_interval=loop_interval,
                terminate_on_failure=terminate_on_failure
            )
            
            if not target_element:
                retry_panel = OutputDecorator.create_step_panel(
                    "查找失败", 
                    f"未找到可点击的目标元素，将进行重试 ({attempt}/{max_attempts})",
                    "warning",
                    "🔄"
                )
                console.print(retry_panel)
                continue
            
            # ==================== 3. 验证元素状态 ====================
            element_ready = False
            
            # 针对元素自身状态进行验证
            if element_condition_type == ConditionType.ElementIsEnabled:
                element_ready = target_element.is_enabled()
            elif element_condition_type == ConditionType.ElementIsVisible:
                element_ready = target_element.is_displayed()
            else:
                element_ready = ConditionVerifier.verify_condition(
                    driver=driver,
                    xpath=target_xpath,
                    condition_type=element_condition_type,
                    timeout=timeout,
                    loop_interval=loop_interval,
                    condition_name="元素状态验证"
                )
            
            if not element_ready:
                retry_panel = OutputDecorator.create_step_panel(
                    "状态检查失败", 
                    f"元素状态不满足点击条件，将进行重试 ({attempt}/{max_attempts})",
                    "warning",
                    "🔄"
                )
                console.print(retry_panel)
                continue
            
            # ==================== 4. 执行点击操作 ====================
            console.print()
            click_panel = OutputDecorator.create_step_panel(
                "执行点击", 
                f"正在执行点击操作: [{Styles.ELEMENT}]{target_xpath}[/{Styles.ELEMENT}]",
                "info",
                "🚀"
            )
            console.print(click_panel)
            
            try:
                # 尝试滚动到元素可见位置
                driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", target_element)
                time.sleep(loop_interval)
                
                # 优先尝试正常点击
                target_element.click()
                
                success_panel = OutputDecorator.create_step_panel(
                    "点击成功", 
                    "点击操作执行完成",
                    "success",
                    "✅"
                )
                console.print(success_panel)
                
            except ElementClickInterceptedException:
                # 处理点击被拦截的情况
                warning_panel = OutputDecorator.create_step_panel(
                    "点击被拦截", 
                    "正常点击被拦截，尝试JavaScript点击",
                    "warning",
                    "⚠️"
                )
                console.print(warning_panel)
                
                driver.execute_script("arguments[0].click();", target_element)
                
                success_panel = OutputDecorator.create_step_panel(
                    "点击成功", 
                    "JavaScript点击执行完成",
                    "success",
                    "✅"
                )
                console.print(success_panel)
            except Exception as e:
                error_panel = OutputDecorator.create_step_panel(
                    "点击失败", 
                    f"点击操作发生错误: {str(e)}",
                    "error",
                    "❌"
                )
                console.print(error_panel)
                continue
            
            # ==================== 5. 后置条件验证 ====================
            if post_condition_xpath:
                post_conditions_met = ConditionVerifier.verify_condition(
                    driver=driver,
                    xpath=post_condition_xpath,
                    condition_type=post_condition_type,
                    expected_value=post_condition_value,
                    timeout=timeout,
                    loop_interval=loop_interval,
                    condition_name="执行后条件验证"
                )
                
                if not post_conditions_met:
                    if terminate_on_failure and attempt >= max_attempts:
                        console.print()
                        error_panel = OutputDecorator.create_step_panel(
                            "操作终止", 
                            "后置条件未满足，程序终止执行",
                            "error",
                            "🚨"
                        )
                        console.print(error_panel)
                        exit(0)
                    
                    retry_panel = OutputDecorator.create_step_panel(
                        "重试操作", 
                        f"后置条件未满足，将进行重试 ({attempt}/{max_attempts})",
                        "warning",
                        "🔄"
                    )
                    console.print(retry_panel)
                    continue
            
            # ==================== 6. 操作成功完成 ====================
            console.print()
            summary_table = Table(show_header=False, box=None, padding=(0, 1))
            summary_table.add_column("项目", style=Styles.CONDITION, width=12)
            summary_table.add_column("结果", style=Styles.INFO)
            
            summary_table.add_row("操作类型", "鼠标点击")
            summary_table.add_row("步骤名称", step_name)
            summary_table.add_row("尝试次数", f"{attempt}/{max_attempts}")
            summary_table.add_row("目标元素", target_xpath)
            summary_table.add_row("执行结果", "✅ 成功")
            
            summary_panel = OutputDecorator.create_operation_panel(
                "操作完成",
                summary_table,
                "green",
                DOUBLE
            )
            console.print(summary_panel)
            console.print()
            
            return True

        # ==================== 7. 所有尝试都失败 ====================
        error_table = Table(show_header=False, box=None, padding=(0, 1))
        error_table.add_column("项目", style=Styles.CONDITION, width=12)
        error_table.add_column("结果", style=Styles.INFO)
        
        error_table.add_row("操作类型", "鼠标点击")
        error_table.add_row("步骤名称", step_name)
        error_table.add_row("最大尝试", f"{max_attempts}次")
        error_table.add_row("目标元素", target_xpath)
        error_table.add_row("执行结果", "❌ 失败")
        
        error_panel = OutputDecorator.create_operation_panel(
            "操作失败",
            error_table,
            "red",
            HEAVY
        )
        console.print(error_panel)
        console.print()
        
        return False

# ------------------------------
# 键盘操作工具类
# ------------------------------
class KeyboardOperator:
    """键盘操作工具类，提供带条件验证的键盘输入操作"""
    
    @staticmethod
    def input_text(
        driver: WebDriver,
        target_xpath: str,
        input_text: str,
        step_name: str = "输入操作",
        # 操作前条件参数
        pre_condition_xpath: str = None,
        pre_condition_type: ConditionType = None,
        pre_condition_value: str = None,
        # 操作后条件参数
        post_condition_xpath: str = None,
        post_condition_type: ConditionType = None,
        post_condition_value: str = None,
        # 输入框状态条件
        element_condition_type: ConditionType = ConditionType.ElementIsEnabled,
        # 输入选项
        clear_before_input: bool = True,
        press_enter_after: bool = False,
        # 通用参数
        timeout: int = 10,
        retry_count: int = 0,
        loop_interval: float = 0.1,
        terminate_on_failure: bool = False
    ) -> bool:
        """
        带条件验证的文本输入操作
        """
        max_attempts = retry_count + 1
        attempt = 0
        
        while attempt < max_attempts:
            attempt += 1
            
            # 操作头部
            OutputDecorator.print_operation_header("键盘输入", step_name, "⌨️")
            
            # 创建操作信息面板
            input_info_table = Table(show_header=False, box=None, padding=(0, 1))
            input_info_table.add_column("属性", style=Styles.CONDITION, width=12)
            input_info_table.add_column("值", style=Styles.INFO)
            
            input_info_table.add_row("操作类型", "键盘输入")
            input_info_table.add_row("输入内容", f"[{Styles.HIGHLIGHT}]{input_text}[/{Styles.HIGHLIGHT}]")
            input_info_table.add_row("目标元素", f"[{Styles.ELEMENT}]{target_xpath}[/{Styles.ELEMENT}]")
            input_info_table.add_row("清空输入", "✅" if clear_before_input else "❌")
            input_info_table.add_row("回车确认", "✅" if press_enter_after else "❌")
            
            action_panel = OutputDecorator.create_step_panel(
                "操作配置", 
                input_info_table,
                "info",
                "⚙️"
            )
            console.print(action_panel)
            
            # ==================== 1. 前置条件验证 ====================
            if pre_condition_xpath:
                pre_conditions_met = ConditionVerifier.verify_condition(
                    driver=driver,
                    xpath=pre_condition_xpath,
                    condition_type=pre_condition_type,
                    expected_value=pre_condition_value,
                    timeout=timeout,
                    loop_interval=loop_interval,
                    condition_name="执行前条件验证"
                )
                
                if not pre_conditions_met:
                    if terminate_on_failure:
                        console.print()
                        error_panel = OutputDecorator.create_step_panel(
                            "操作终止", 
                            "前置条件未满足，程序终止执行",
                            "error",
                            "🚨"
                        )
                        console.print(error_panel)
                        exit(0)
                    
                    retry_panel = OutputDecorator.create_step_panel(
                        "重试操作", 
                        f"前置条件未满足，将进行重试 ({attempt}/{max_attempts})",
                        "warning",
                        "🔄"
                    )
                    console.print(retry_panel)
                    continue
            
            # ==================== 2. 查找目标元素 ====================
            console.print()
            target_element = ElementFinder.find_element(
                driver=driver,
                target_xpath=target_xpath,
                step_name=f"{step_name} - 查找输入框",
                timeout=timeout,
                retry_count=0,
                loop_interval=loop_interval,
                terminate_on_failure=terminate_on_failure
            )
            
            if not target_element:
                retry_panel = OutputDecorator.create_step_panel(
                    "查找失败", 
                    f"未找到目标输入框元素，将进行重试 ({attempt}/{max_attempts})",
                    "warning",
                    "🔄"
                )
                console.print(retry_panel)
                continue
            
            # ==================== 3. 验证输入框状态 ====================
            element_ready = False
            
            if element_condition_type == ConditionType.ElementIsEnabled:
                element_ready = target_element.is_enabled()
            elif element_condition_type == ConditionType.ElementIsVisible:
                element_ready = target_element.is_displayed()
            else:
                element_ready = ConditionVerifier.verify_condition(
                    driver=driver,
                    xpath=target_xpath,
                    condition_type=element_condition_type,
                    timeout=timeout,
                    loop_interval=loop_interval,
                    condition_name="输入框状态验证"
                )
            
            if not element_ready:
                retry_panel = OutputDecorator.create_step_panel(
                    "状态检查失败", 
                    f"输入框状态不满足输入条件，将进行重试 ({attempt}/{max_attempts})",
                    "warning",
                    "🔄"
                )
                console.print(retry_panel)
                continue
            
            # ==================== 4. 执行输入操作 ====================
            console.print()
            input_panel = OutputDecorator.create_step_panel(
                "执行输入", 
                f"正在执行输入操作: [{Styles.HIGHLIGHT}]{input_text}[/{Styles.HIGHLIGHT}]",
                "info",
                "🚀"
            )
            console.print(input_panel)
            
            try:
                # 滚动到元素可见位置
                driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", target_element)
                time.sleep(loop_interval)
                
                # 点击输入框获取焦点
                target_element.click()
                time.sleep(loop_interval)
                
                # 输入前清空
                if clear_before_input:
                    target_element.clear()
                    target_element.send_keys(Keys.CONTROL + "a")
                    target_element.send_keys(Keys.DELETE)
                
                # 输入文本
                target_element.send_keys(input_text)
                time.sleep(loop_interval)
                
                # 输入后按回车
                if press_enter_after:
                    target_element.send_keys(Keys.ENTER)
                    console.print()
                    enter_panel = OutputDecorator.create_step_panel(
                        "回车确认", 
                        "已按下回车键确认输入",
                        "info",
                        "↵"
                    )
                    console.print(enter_panel)
                
                success_panel = OutputDecorator.create_step_panel(
                    "输入成功", 
                    "输入操作执行完成",
                    "success",
                    "✅"
                )
                console.print(success_panel)
                
            except Exception as e:
                error_panel = OutputDecorator.create_step_panel(
                    "输入失败", 
                    f"输入操作发生错误: {str(e)}",
                    "error",
                    "❌"
                )
                console.print(error_panel)
                continue
            
            # ==================== 5. 后置条件验证 ====================
            if post_condition_xpath:
                post_conditions_met = ConditionVerifier.verify_condition(
                    driver=driver,
                    xpath=post_condition_xpath,
                    condition_type=post_condition_type,
                    expected_value=post_condition_value,
                    timeout=timeout,
                    loop_interval=loop_interval,
                    condition_name="执行后条件验证"
                )
                
                if not post_conditions_met:
                    if terminate_on_failure and attempt >= max_attempts:
                        console.print()
                        error_panel = OutputDecorator.create_step_panel(
                            "操作终止", 
                            "后置条件未满足，程序终止执行",
                            "error",
                            "🚨"
                        )
                        console.print(error_panel)
                        exit(0)
                    
                    retry_panel = OutputDecorator.create_step_panel(
                        "重试操作", 
                        f"后置条件未满足，将进行重试 ({attempt}/{max_attempts})",
                        "warning",
                        "🔄"
                    )
                    console.print(retry_panel)
                    continue
            
            # ==================== 6. 操作成功完成 ====================
            console.print()
            summary_table = Table(show_header=False, box=None, padding=(0, 1))
            summary_table.add_column("项目", style=Styles.CONDITION, width=12)
            summary_table.add_column("结果", style=Styles.INFO)
            
            summary_table.add_row("操作类型", "键盘输入")
            summary_table.add_row("步骤名称", step_name)
            summary_table.add_row("尝试次数", f"{attempt}/{max_attempts}")
            summary_table.add_row("输入内容", input_text)
            summary_table.add_row("目标元素", target_xpath)
            summary_table.add_row("执行结果", "✅ 成功")
            
            summary_panel = OutputDecorator.create_operation_panel(
                "操作完成",
                summary_table,
                "green",
                DOUBLE
            )
            console.print(summary_panel)
            console.print()
            
            return True

        # ==================== 7. 所有尝试都失败 ====================
        error_table = Table(show_header=False, box=None, padding=(0, 1))
        error_table.add_column("项目", style=Styles.CONDITION, width=12)
        error_table.add_column("结果", style=Styles.INFO)
        
        error_table.add_row("操作类型", "键盘输入")
        error_table.add_row("步骤名称", step_name)
        error_table.add_row("最大尝试", f"{max_attempts}次")
        error_table.add_row("输入内容", input_text)
        error_table.add_row("目标元素", target_xpath)
        error_table.add_row("执行结果", "❌ 失败")
        
        error_panel = OutputDecorator.create_operation_panel(
            "操作失败",
            error_table,
            "red",
            HEAVY
        )
        console.print(error_panel)
        console.print()
        
        return False

# ------------------------------
# 浏览器控制工具类
# ------------------------------
class BrowserController:
    """浏览器控制工具类，负责浏览器进程管理和驱动初始化"""
    
    @staticmethod
    def show_message(parent_hwnd: int = 0, title: str = '提示', text: str = '默认文本', msg_type: int = 0) -> int:
        """显示自定义消息框"""
        return ctypes.windll.user32.MessageBoxW(parent_hwnd, text, title, msg_type)
    
    @staticmethod
    def is_process_running(process_name: str = "msedge.exe") -> bool:
        """检查是否存在指定名称的进程"""
        for proc in psutil.process_iter(['name']):
            if proc.info['name'] == process_name:
                return True
        return False
    
    @staticmethod
    def is_debug_mode_active(local: str = "127.0.0.1", port: str = "9652") -> bool:
        """检查调试模式是否激活"""
        url = f"http://{local}:{port}/json/version"
        try:
            response = requests.get(url=url, timeout=5)
            return response.status_code == 200
        except Exception as e:
            console.print(f"[{Styles.ERROR}]调试模式检查错误: {e}[/{Styles.ERROR}]")
            return False
    
    @staticmethod
    def close_all_processes(process_name: str = "msedge.exe") -> bool:
        """关闭所有指定名称的进程"""
        success = True
        processes_closed = 0
        
        console.print()
        console.rule("🔄 进程管理", style=Styles.OPERATION)
        console.print()
        
        for proc in psutil.process_iter(['pid', 'name']):
            if process_name == proc.info['name']:
                try:
                    proc.kill()
                    processes_closed += 1
                    console.print(f"✅ [{Styles.SUCCESS}]已关闭进程 PID: {proc.info['pid']}[/{Styles.SUCCESS}]")
                except Exception as e:
                    console.print(f"❌ [{Styles.ERROR}]关闭进程 PID: {proc.info['pid']} 失败: {e}[/{Styles.ERROR}]")
                    success = False
        
        console.print()
        summary_table = Table(show_header=False, box=None, padding=(0, 1))
        summary_table.add_column("项目", style=Styles.CONDITION, width=12)
        summary_table.add_column("结果", style=Styles.INFO)
        
        summary_table.add_row("成功关闭", f"{processes_closed} 个进程")
        summary_table.add_row("操作结果", "✅ 成功" if success else "❌ 部分失败")
        
        summary_panel = OutputDecorator.create_operation_panel(
            "进程管理完成",
            summary_table,
            "green" if success else "red",
            DOUBLE
        )
        console.print(summary_panel)
        console.print()
        
        return success
    
    @staticmethod
    def start_debug_mode_browser(
        local: str = "127.0.0.1",
        debug_port: int = 9652,
        user_data_dir: str = None,
        with_extensions: bool = False
    ):
        """启动带调试模式的浏览器"""
        console.print()
        console.rule("🌐 浏览器启动", style=Styles.OPERATION)
        console.print()
        
        # 构建启动命令
        if user_data_dir:
            command = rf'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --remote-debugging-port={debug_port} --user-data-dir="{user_data_dir}" "http://{local}:{debug_port}/json/version"'
        else:
            command = rf'"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --remote-debugging-port={debug_port} "http://{local}:{debug_port}/json/version"'
        
        # 显示启动信息
        info_table = Table(show_header=False, box=None, padding=(0, 1))
        info_table.add_column("属性", style=Styles.CONDITION, width=12)
        info_table.add_column("值", style=Styles.INFO)
        
        info_table.add_row("调试端口", f"{debug_port}")
        info_table.add_row("用户数据目录", f"{user_data_dir or '默认'}")
        
        console.print(OutputDecorator.create_step_panel(
            "启动配置", 
            info_table,
            "info",
            "⚙️"
        ))
        console.print()
        
        # 启动新进程
        CREATE_NEW_CONSOLE = 0x00000010
        subprocess.Popen(command, shell=True, creationflags=CREATE_NEW_CONSOLE)
        console.print(f"✅ [{Styles.SUCCESS}]已启动调试模式浏览器，端口: {debug_port}[/{Styles.SUCCESS}]")
        
        # 等待浏览器启动
        with console.status("[bold blue]等待浏览器启动...[/bold blue]", spinner="dots"):
            time.sleep(3)
    
    @staticmethod
    def create_driver_instance(
        local: str = "127.0.0.1", 
        port: int = 9652
    ) -> typing.Tuple[WebDriver, WebDriverWait, ActionChains]:
        """创建WebDriver、WebDriverWait和ActionChains实例"""
        console.print()
        console.rule("⚙️ 驱动初始化", style=Styles.OPERATION)
        console.print()
        
        options = Options()
        options.add_experimental_option("debuggerAddress", f"{local}:{port}")
        service = Service()
        driver = WebDriver(options=options, service=service)
        wait = WebDriverWait(driver=driver, timeout=10)
        actions = ActionChains(driver=driver)
        
        console.print(f"✅ [{Styles.SUCCESS}]WebDriver实例创建成功[/{Styles.SUCCESS}]")
        return driver, wait, actions
    
    @staticmethod
    def connect_debug_browser(
        local: str = "127.0.0.1",
        debug_port: int = 9652,
        user_data_dir: str = None
    ) -> typing.Tuple[WebDriver, WebDriverWait, ActionChains]:
        """连接到调试模式浏览器，如未启动则自动启动"""
        console.print()
        console.rule("🌐 浏览器连接流程", style=Styles.OPERATION)
        console.print()
        
        # 检查进程是否存在
        if not BrowserController.is_process_running():
            console.print(f"ℹ️ [{Styles.INFO}]未检测到浏览器进程，启动新浏览器[/{Styles.INFO}]")
            BrowserController.start_debug_mode_browser(
                local=local, 
                debug_port=debug_port, 
                user_data_dir=user_data_dir
            )
        else:
            # 检查调试模式是否激活
            if not BrowserController.is_debug_mode_active(local=local, port=str(debug_port)):
                if user_data_dir is not None:
                    BrowserController.start_debug_mode_browser(
                        local=local, 
                        debug_port=debug_port, 
                        user_data_dir=user_data_dir
                    )
                else:
                    # 询问用户是否关闭现有进程
                    result = BrowserController.show_message(
                        title="提示",
                        text="检测到浏览器进程但未启用调试模式，是否关闭所有浏览器进程?",
                        msg_type=4  # YES/NO 按钮
                    )
                    if result == 6:  # YES
                        BrowserController.close_all_processes()
                        BrowserController.start_debug_mode_browser(
                            local=local, 
                            debug_port=debug_port
                        )
                    else:  # NO
                        console.print()
                        error_panel = OutputDecorator.create_operation_panel(
                            "操作取消",
                            "用户取消操作，程序退出",
                            "red",
                            HEAVY
                        )
                        console.print(error_panel)
                        exit(0)
        
        # 连接到调试浏览器
        return BrowserController.create_driver_instance(local=local, port=debug_port)
    
    @staticmethod
    def switch_to_active_tab(driver: WebDriver, local: str = "127.0.0.1", port: int = 9652) -> None:
        """切换到当前激活的标签页"""
        try:
            debug_data = requests.get(f"http://{local}:{port}/json", timeout=5).json()
            if not isinstance(debug_data, list):
                console.print(f"❌ [{Styles.ERROR}]调试接口返回数据格式不正确[/{Styles.ERROR}]")
                return
                
            # 筛选有效的页面
            valid_pages = [
                page for page in debug_data 
                if page.get('type') == "page" and 
                not page.get('url', '').lower().startswith(("chrome-devtools", "chrome-extension"))
            ]
            
            if valid_pages:
                active_tab_id = valid_pages[0]['id']
                driver.switch_to.window(active_tab_id)
                console.print(f"✅ [{Styles.SUCCESS}]已切换到激活标签页[/{Styles.SUCCESS}]")
        except Exception as e:
            console.print(f"❌ [{Styles.ERROR}]切换标签页失败: {e}[/{Styles.ERROR}]")

# ------------------------------
# 使用示例
# ------------------------------
if __name__ == "__main__":
    try:
        # 程序开始
        console.print()
        console.rule("🚀 自动化脚本启动", style="bold green")
        console.print()
        
        # 连接到调试模式浏览器
        driver, wait, actions = BrowserController.connect_debug_browser(
            local="127.0.0.1",
            debug_port=9652
        )
        
        # 切换到激活标签页
        BrowserController.switch_to_active_tab(driver, port=9652)
        
        # 示例1: 简单的元素查找
        element = ElementFinder.find_element(
            driver=driver,
            target_xpath="//input[contains(@placeholder,'请输入')]",
            step_name="查找输入框示例",
            timeout=5
        )
        
        if element:
            # 示例2: 带条件的输入操作
            KeyboardOperator.input_text(
                driver=driver,
                target_xpath="//input[contains(@placeholder,'请输入')]",
                input_text="女装T恤",
                step_name="输入商品标题示例",
                pre_condition_xpath="//input[contains(@placeholder,'请输入')]",
                pre_condition_type=ConditionType.InputValueIsNull,
                post_condition_xpath="//input[contains(@placeholder,'请输入')]",
                post_condition_type=ConditionType.InputValueEqual,
                post_condition_value="女装T恤",
                clear_before_input=True,
                press_enter_after=False,
                timeout=5,
                retry_count=1
            )
        
        console.print()
        console.rule("✅ 自动化操作完成", style="bold green")
        console.print()
        
    except Exception as e:
        console.print()
        error_panel = OutputDecorator.create_operation_panel(
            "脚本执行错误",
            f"错误信息: {str(e)}",
            "red",
            HEAVY
        )
        console.print(error_panel)
        console.print()